//
// Created by 蓝布鲁 on 2017/3/28.
// Copyright (c) 2017 蓝布鲁. All rights reserved.
//

#import "SigninViewController.h"
#import "SigninModel.h"
#import "UserInfoModel.h"
#import <AVFoundation/AVFoundation.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>

@interface SigninViewController()<AVCaptureMetadataOutputObjectsDelegate>

@property (nonatomic, retain) AVCaptureSession *session;        // 会话

@property (nonatomic, retain) AVCaptureVideoPreviewLayer *previewLayer;     // 图层

@property (nonatomic, retain) AMapLocationManager *locationManager;         // 高德地图
@property (nonatomic, retain) UIImageView *scanImage;                       // 扫描背景图


// 请求获得的数据
@property (nonatomic, retain) NSString *scanString;             // 扫描结果
@property (nonatomic, assign) double longitude;                // 经度
@property (nonatomic, assign) double latitude;                 // 纬度
@property (nonatomic, retain) SigninModel *scanModel;           // 二维码模型


@property (nonatomic, assign) NSInteger lock;               // 锁.初始值为2,两次请求以后才解锁

@end

@implementation SigninViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"签到";
    self.view.backgroundColor = UIColor.whiteColor;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.hidesBottomBarWhenPushed = YES;
    self.lock = 2;
    
    // 背景设置
    self.scanImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.scanImage.image = [UIImage imageNamed:@"scan_qrcode"];
    [self.view addSubview:self.scanImage];

    // 设置定位
    [self setupLocation];

    // 开始签到
    [self startSignin];

}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [SVProgressHUD dismiss];

    // 停止定位
    [self.locationManager stopUpdatingLocation];
}


#pragma mark - 自定义方法
// 开始签到
-(void)startSignin {
    self.scanImage.hidden = false;
    self.longitude = 0;
    self.latitude = 0;
    self.scanString = [[NSString alloc] init];


    // 1.扫描二维码
    [self setupCodeScanning];

    // 2.定位
    [self getLocation];
}

// 扫描二维码
- (void)setupCodeScanning {
    // 1.获取相机设备
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    // 2.创建输入流
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];

    // 3.创建输出流
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];

    // 4.设置代理,在主线程里刷新
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];

    // 设置扫描范围
    output.rectOfInterest = CGRectMake(0.05, 0.05, 0.9, 0.9);

    // 5.初始化会话
    self.session = [[AVCaptureSession alloc] init];
    // 5.1设置采集率
    [self.session setSessionPreset:AVCaptureSessionPresetHigh];
    // 5.2设置输入流
    [self.session addInput:input];
    // 5.3设置输出流
    [self.session addOutput:output];

    // 6、设置输出数据类型，需要将元数据输出添加到会话后，才能指定元数据类型，否则会报错
    // 设置扫码支持的编码格式(如下设置二维码兼容)
    output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];

    // 7.实例化预览图层
    self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    self.previewLayer.frame = self.view.layer.bounds;

    // 8.将图层插入当前视图
    [self.view.layer insertSublayer:self.previewLayer atIndex:0];

    // 9.启动会话
    [self.session startRunning];
}

// 定位
- (void)setupLocation {
        self.locationManager = [[AMapLocationManager alloc] init];

        [self.locationManager setDelegate:self];

        [self.locationManager setPausesLocationUpdatesAutomatically:NO];

//        [self.locationManager setAllowsBackgroundLocationUpdates:YES];

    // 带逆地理信息的一次定位（返回坐标和地址信息）
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
//   定位超时时间，最低2s，此处设置为10s
    self.locationManager.locationTimeout =10;
//   逆地理请求超时时间，最低2s，此处设置为10s
    self.locationManager.reGeocodeTimeout = 10;
}

-(void)getLocation {
    [self.locationManager requestLocationWithReGeocode:true
                                       completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
                                           if (error)
                                           {
                                               NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);

                                               if (error.code == AMapLocationErrorLocateFailed)
                                               {
                                                   [self signinFailed:1001];
                                                   return;
                                               }
                                           }

//                                           NSLog(@"location:%@", location);
                                           // 经度
                                           self.longitude = location.coordinate.longitude;
                                           // 纬度
                                           self.latitude = location.coordinate.latitude;


                                           if (regeocode)
                                           {
                                               NSLog(@"reGeocode:%@", regeocode);
                                           }
                                           // 请求签到
                                           [self updateSigninInfo];
    }];
}

- (void)updateSigninInfo {
    self.lock--;
    if(self.lock == 0){
        // 如果数据齐全则进行签到
        if (self.latitude && self.longitude && [self.scanString length]) {
            NSLog(@"经度:%lf,纬度:%lf,扫描内容:%@",self.latitude,self.longitude,self.scanString);

            // 1.扫码得到的sting产生NSData
            NSData *data = [self.scanString dataUsingEncoding:NSUTF8StringEncoding];

            // 2.解析NSData为NSDictionary
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data
                                                                options:NSJSONReadingMutableContainers
                                                                  error:nil];

            // 3.初始化模型
            self.scanModel = [[SigninModel alloc] initWithDictionary:dic];

            // 3.1验证二维码是否正确解析
            if(self.scanModel == nil || !self.scanModel.act_id) {
                // 未能解析二维码
                NSLog(@"未能解析的二维码: %@",self.scanString);
                [SVProgressHUD dismiss];
                [self signinFailed:1000];
                return;
            }

            // 4.请求接口签到
            NSDictionary *parameters = @{@"s_id": [UserInfoModel shareInstance].stu_id,
                    @"act_id": @(self.scanModel.act_id), @"device_code": [UserInfoModel shareInstance].deviceCode,
                    @"token": [UserInfoModel shareInstance].token, @"latitude": @(self.latitude), @"longitude": @(self.longitude)};
            [[NetworkTool shareInstance] requireMethodType:POSTType
                                                 URLString:@"SDSY/checkQRcode"
                                                parameters:parameters
                                                   success:^(NSDictionary *respondDictionary) {
                                                       // 提取签到状态码
                                                       NSInteger code = [respondDictionary[@"code"] intValue];
                                                       [SVProgressHUD dismiss];

                                                       // 判断状态码
                                                       if(code == 1) {
                                                           // 签到成功
                                                           [self signinSuccess];
                                                       } else {
                                                           // 签到失败
                                                           [self signinFailed:code];
                                                       }
                                                   } failure:^(NSError *error) {
                        
                    }];





        } else {
            [SVProgressHUD showErrorWithStatus:@"签到失败,未能获取签到数据"];
        }
    }

}

// 签到成功,显示提示信息,返回主页
-(void)signinSuccess {
    // 提示签到成功
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"签到成功"
                                                                   message:[self getLocationString]
                                                            preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *done = [UIAlertAction actionWithTitle:@"确定"
                                                   style:UIAlertActionStyleDefault
                                                 handler:^(UIAlertAction *action) {
                                                     [self.navigationController popToRootViewControllerAnimated:true];
    }];
    [alert addAction:done];
    [self presentViewController:alert animated:true completion:nil];

}

// 签到失败,显示错误信息,选择返回主页或重新扫描
/*
 * code: 1000 未能解析二维码到相应格式
 * code: 1001 未能获得地理位置
 */
-(void)signinFailed:(NSInteger)code {
    NSString *reason = [[NSString alloc] init];

#pragma mark 需要告知签到失败原因
    switch (code) {
        case 0:
            reason = @"未在有效时间内签到";
            break;
        case 2:
            reason = @"一台设备只允许一个学生帐号签到";
            break;
        case 3:         // 未知签到错误
            reason = @"未知原因，扫码签到失败";
            break;
        case 4:
            reason = @"未在有效范围内签到";
            break;
        case 5:
            reason = @"没有预约此活动";
            break;
        case 1000:
            reason = @"未能解析二维码到相应格式";
            break;
        case 1001:
            reason = @"未能获得地理位置";
            break;
        default:
            reason = @"code default";
            break;
    }



    // 提示签到失败
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"签到失败"
                                                                   message:[NSString stringWithFormat:@"%@\n 错误原因：%@",[self getLocationString],reason]
                                                            preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *done = [UIAlertAction actionWithTitle:@"确定"
                                                   style:UIAlertActionStyleDefault
                                                 handler:^(UIAlertAction *action) {
                                                     [self.navigationController popToRootViewControllerAnimated:true];
                                                 }];
    [alert addAction:done];

    [self presentViewController:alert animated:true completion:nil];
}

- (NSString *)getLocationString{
    return [NSString stringWithFormat:@"当前经度:%.6lf 纬度:%.6lf",self.longitude, self.latitude];
}


#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    // 因为获取地点时间较长,所以需要等待
    [SVProgressHUD showWithStatus:@"定位中..."];
    
    // 1.如果扫描完成.停止会话
    [self.session stopRunning];

    // 2.删除预览图层
    [self.previewLayer removeFromSuperlayer];

    // 3.获取扫描结果
    if (metadataObjects.count > 0) {
        AVMetadataMachineReadableCodeObject *obj = metadataObjects[0];
        self.scanString = obj.stringValue;
    }
    // 请求签到
    [self updateSigninInfo];



    // 隐藏扫描图案
    self.scanImage.hidden = true;
}

@end
